import 'package:flutter/material.dart';
import 'cupertino_localisations_delegate.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'lang_index.dart' show AppLocalizationsDelegate,WXLang;
import 'support_config.dart';

typedef void LocaleChangeCallback(Locale locale);

class WXLocales {
    static LanguageConfig appConfig;

    static LocaleChangeCallback onLocaleChanged;

    /// 是否跟随系统，默认跟随系统语言切换
    static bool _isFollowSystem = true;
    /// 系统默认语言
    static Locale systemLocale;
    /// 主要用于处理用户缓存的语言，用于再次打开APP时使用
    static Locale firstLocale;

    static void init(LanguageConfig config, {bool isFollowSystem ,Locale first}) {
        appConfig = config;
        firstLocale = first;
        isFollowSystem = isFollowSystem;
    }

    static void setFollowSystem(bool isFollowSystem) {
        _isFollowSystem = isFollowSystem;
    }
    /// LocaleResolutionCallback
    static LocaleResolutionCallback localeResolutionCallback = (deviceLocale, supportedLocals) {
        if (!_isFollowSystem) {
            systemLocale = deviceLocale;
            return null;
        }
//        wxLog(
//                "deviceLocal: ${deviceLocale != null ? deviceLocale.languageCode : "没有获取到地址信息哦"}");
//        print("languageCode: ${deviceLocale.languageCode},  countryCode: ${deviceLocale.countryCode}");

        if(firstLocale != null) { /// 再次打开APP时需要用之前用户的语言设置
            systemLocale = deviceLocale;
            deviceLocale = firstLocale;
            firstLocale = null;

            return deviceLocale;
        }

        systemLocale = appConfig.supportLocale;

        if (deviceLocale != null && deviceLocale.languageCode != null) {
            Locale containerLocale = supportedLocals.firstWhere(
                            (element) => element.languageCode == deviceLocale.languageCode);
            systemLocale = containerLocale != null
                    ? containerLocale
                    : appConfig.supportLocale;

//            wxLog("supportedLocal: $containerLocale");
        }

        return systemLocale;
    };
    /// localizationsDelegates
    static localizationsDelegates(AppLocalizationsDelegate delegate, {LocalizationsDelegate forceDelegate}) {
        return [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            forceDelegate,
            delegate,
            FallbackCupertinoLocalisationsDelegate(),
        ];
    }
    /// supportedLocales
    static Iterable<Locale> supportedLocales = appConfig.supportLocales();

    ///　如果设置title的话需要用这个才可以实现title的国际化
    static GenerateAppTitle generateAppTitle = (context) => WXLang.$t("title");

}